<template>
  <el-dialog append-to-body v-model="dialogVisible" title="上传图片" width="950px" @close="dialogVisible = false">
    <el-form ref="postForm" label-width="80px" class="ruleForm" :model="form" :rules="rules">
      <el-form-item label="分类：">
        <el-col :span="22">
          <el-select v-model="form.category" placeholder="请选择分类">
            <el-option v-for="item in categorys" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="图片：" required>
        <el-col :span="24">
          <el-upload multiple ref="uploadRef" action="#" :class="{'upload-max': form.file?.length >= props.limit}" accept="image/jpeg,image/gif,image/png,image/bmp" :auto-upload="false" list-type="picture-card" :limit="props.limit" :on-change="changeImageChange" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-image-viewer v-if="dialogImageVisible" :url-list="[dialogImageUrl]" @close="dialogImageVisible = false" />
        </el-col>
      </el-form-item>
    </el-form>
    <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button v-if="isSubmit" disabled :icon="Loading" type="primary">确定</el-button>
      <el-button v-else type="primary" @click="handleSave()">确定</el-button>
    </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { Plus,Loading } from '@element-plus/icons-vue'
import type { UploadProps, UploadFile,UploadFiles,UploadInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import {ref,reactive, computed,watch } from 'vue'
import {FileCategorys,UploadImage} from '@/api/file'
import { FileType } from '@/utils/enum'

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false
    },
    category: {
      type: Number,
      default: 0
    },
    limit: {
      type: Number,
      default: 15
    }
  })
  const form = ref<UploadImageCommand>({
    file: [],
    category: props.category,
  })
  const rules = reactive({
    file: [{ required: true, message: '请上传文件', trigger: 'blur' }]
  })
  /** 分类列表 */
  const categorys = ref<any>([])
    /** 查看图片 */
  const dialogImageVisible = ref<boolean>(false)
    /** 查看图片地址 */
  const dialogImageUrl = ref<string>('')
  /** 是否提交 */
  const isSubmit = ref<boolean>(false)
    const uploadRef = ref<UploadInstance>();
  /**
   * 加载分类
   */
  const loadCategorys = ():void => {
    FileCategorys(FileType.Image).then((res:ServiceResponse<FileCategory[]>) => {
      categorys.value = res.data
    })
  }
  const changeImageChange: UploadProps['onChange'] = (uploadFile: UploadFile) => {
    form.value.file.push(uploadFile)
  }
  
  const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile : UploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogImageVisible.value = true
  }
  const handleRemove: UploadProps['onRemove'] = (uploadFile:UploadFile, uploadFiles:UploadFiles) => {
    var files:any = []
    uploadFiles.forEach( (item:any) => {files.push(item)})
    form.value.file = files
  }
  const handleSave = ():void => {
    isSubmit.value = true
    if(form.value.file.length === 0) {
      isSubmit.value = false  
       ElMessage.error("请上传图片")
       return
    }
    let list: FileEditor[] = []
    form.value.file.forEach((item : any) => {
      const formData = new FormData()
        formData.append('category',form.value.category.toString())
        formData.append('file', item.raw)
       
         UploadImage(formData).then((res: ServiceResponse<FileEditor>) => {
          if(res.success) {
            if(res.data) {
              list.push(res.data)
              if(list.length === form.value.file.length) {
                emit('on-confirm', list)
                isSubmit.value = false
                ElMessage.success("上传成功")
              }
            }
          } else {
            isSubmit.value = false
            ElMessage.error(res.msg)
          }
                   
        })
    })
  }
  //定义事件
  interface Emits {
    (e: 'update:visible', dialogVisible: boolean): void,
    (e: 'on-confirm', value: FileEditor[] ): void
  }
  const emit = defineEmits<Emits>()

  //子组件不能修改Props值（通过get set解决）
  const dialogVisible = computed({
    get() {
        return props.visible
    },
    set(visible: boolean) {
        emit('update:visible', visible)
    }
  })
  watch(() =>props.visible,(visible) => {
    if(visible) {
      form.value.category = props.category
      console.log(props.category)
      form.value.file = []
      uploadRef.value?.clearFiles()
      loadCategorys()
    }
  })
</script>
<style lang="scss" scoped>
@import "@/assets/styles/mixin.scss";
@import "@/assets/styles/formPage.scss";
::v-deep .el-upload-list__item-thumbnail {
  object-fit: scale-down;
}

.upload-max {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}
</style>